//
//  LSZVideoWebView.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/1/4.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZVideoWebView.h"
#import "WYWebProgressLayer.h"
#import <YYKeyboardManager/YYKeyboardManager.h>
#import "LSZVideoWebView+LCPingLun.h"

#define scriptNameArr @[@"GetUserCode",@"share",@"login",@"title"]

@interface LSZVideoWebView ()
<UIScrollViewDelegate,YYKeyboardObserver>
{
    WYWebProgressLayer *_progressLayer; ///< 网页加载进度条
}

@property (nonatomic,strong) YYKeyboardManager *manager;

@property (nonatomic,assign) NSInteger checkLoginSum;//校验登录 用来过滤掉多次验证

@end

@implementation LSZVideoWebView

#pragma mark -  页面  -
- (void)viewDidLoad {
    [super viewDidLoad];
    /**增加侧滑返回,无其他作用*/
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, ScreenHeight)];
    [self.view addSubview:view];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.view bringSubviewToFront:view];
    });

    [self setupWebView];
    if (_LCPlayer.kstatus == LCMusicPlayerStatusPlaying ){
        self.PlayAudio++;
        [_LCPlayer pause];//暂停播放
        _LCPlayer.comeFrome = 1;
    }
    _manager = [YYKeyboardManager defaultManager];
    [_manager addObserver:self];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lcApplicationEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(lcApplicationEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    //当前为非WiFi网络,将使用流量播放 继续播放 
    //已自动使用WiFi播放
    [self createPingLun];
}
-(void)lcApplicationEnterBackground {
    NSString *JSString = @"pauseVideo();pauseAudio();";
    NSLog(@"%@", JSString);
    [self.webView evaluateJavaScript:JSString completionHandler:nil];
}
- (void)lcApplicationEnterForeground {
//    NSString *JSString = @"playVideo();playAudio();";
//    [self.webView evaluateJavaScript:JSString completionHandler:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:scriptNameArr[i]];
    }
    //监听键盘
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    for (NSInteger i = 0; i < scriptNameArr.count; i++) {
        [self.webView.configuration.userContentController removeScriptMessageHandlerForName:scriptNameArr[i]];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}

- (void)dealloc {
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
    _LCPlayer.comeFrome = 0;
    if (self.PlayAudio>0) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_LCPlayer play];//继续播放
        });
    }

    _webView.scrollView.delegate = nil;
    _webView.UIDelegate = nil;
    _webView.navigationDelegate = nil;
    [[YYKeyboardManager defaultManager] removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];

    NSLog(@"dealloc");
}

-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setupWebView{
    if (self.title.length == 0 && self.model.title.length > 0) {
        self.title = self.model.title;
    }
    if (self.title.length == 0 && self.searchKeyContentMg.title.length > 0) {
        self.title = self.searchKeyContentMg.title;
    }
    self.view.backgroundColor = RGBColor(236, 236, 236);

    self.navigationController.navigationItem.hidesBackButton = YES;//隐藏系统的返回按钮
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home_nav_button_back"] style:UIBarButtonItemStyleDone target:self action:@selector(back)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"点点点"] style:UIBarButtonItemStyleDone target:self action:@selector(rightBtnAction)];
    
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    NSMutableString *javascript = [NSMutableString string];
    //获取视频音频的暂停和播放
    [javascript appendString:@"var videos=document.getElementsByTagName('video');function pauseVideo(){var len=videos.length;for(var i=0;i<len;i++){videos[i].pause();}}function playVideo(){var len=videos.length;for(var i=0;i<len;i++){videos[i].play();}}  var audios=document.getElementsByTagName('audio');function pauseAudio(){var len=audios.length;for(var i=0;i<len;i++){audios[i].pause();}}  function playAudio(){var len=audios.length;for(var i=0;i<len;i++){audios[i].play();}}"];
    //获取Title
    [javascript appendString:@"var titles=document.getElementsByTagName('h1');window.webkit.messageHandlers.title.postMessage(titles[0].innerHTML);"];
    //登录
    [javascript appendString:[NSString stringWithFormat:@"login_ac('%@%@",[_UserM usercode],@"');"]];
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javascript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:userScript];
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
    if (iPhoneX) {
        self.webView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height - NAVIGATION_BAR_HEIGHT-15);
    }else{
        self.webView.frame = CGRectMake(0, NAVIGATION_BAR_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height - NAVIGATION_BAR_HEIGHT);
    }
    self.webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
    
    
    [self.view addSubview:self.webView];
    self.webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    self.webView.scrollView.delegate = self;
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.link]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url];//创建NSURLRequest
    [self.webView loadRequest:request];//加载
    
}
///禁止键盘弹出时WKWebView自动滑动
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}
///分享 右边按钮
-(void)rightBtnAction {
    _manager.keyboardVisible ? [[[UIApplication sharedApplication] keyWindow] endEditing:YES] : -1;

    NSString *shareUrl,*title;
    if (self.searchKeyContentMg) {
        shareUrl = self.searchKeyContentMg.shareUrl;
        title = self.searchKeyContentMg.title;
    }
    if (self.model) {
        shareUrl = self.model.shareUrl;
        title = self.model.title;
    }
    if (shareUrl == nil) {
        shareUrl = self.link;
    }
    if (self.title.length > 0) {
        title = self.title;
    }
    if (self.webView.URL.absoluteString.length > 0) {
//    NSLog(@"self.webView.URL.absoluteString = %@", self.webView.URL.absoluteString);
        shareUrl = self.webView.URL.absoluteString;
    }
    //分享类型  网页分享
    [self shareShengJingMessageWithImageArray:@[@"我的_设置_关于"] url:shareUrl title:title contentMessage:@"今日圣经" type:SSDKContentTypeWebPage];
}

- (void)sendUserCode{
    NSArray *array = @[@"usercode = '",
                       [_UserM usercode],
                       @"';",
                       //                       @"for(var t = Date.now();Date.now() - t <= 1000;);",
                       @"login_ac('",
                       [_UserM usercode],
                       @"');"
                       ];
    NSString *JSString = [array componentsJoinedByString:@""];
    NSLog(@"%@", JSString);
    [self.webView evaluateJavaScript:JSString completionHandler:nil];
    /**for(var t = Date.now();Date.now() - t <= 1000;); */
}
#pragma mark -  JS与WKWebView 交互  -
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
    @try {
        if([message.name isEqualToString:@"GetUserCode"]){
            [self sendUserCode];// 直接调用JS注入的方法即可
        }
        if([message.name isEqualToString:@"share"]){
            NSLog(@"message.body = %@", message.body);
            [self rightBtnAction];
        }
        if([message.name isEqualToString:@"login"]){
            NSLog(@"login message.body = %@", message.body);
            pushAccLoginVC;
        }
        if([message.name isEqualToString:@"title"]){
            NSString *title = message.body;
            if (title.length > 0) {
                NSLog(@"title message.body = %@", message.body);
                self.title = title;
            }
        }
    } @catch (NSException *exception) {
        
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
        });
    }
}
#pragma mark -  网页加载前处理
/** 跳转处理 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:
(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *url = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    if (self.beautifulEssayListArray) {
        for (NSInteger i = 0; i < self.beautifulEssayListArray.count; i++) {
            if ([self.beautifulEssayListArray[i].remoteUrl isEqualToString:navigationAction.request.URL.absoluteString]) {
                self.model = self.beautifulEssayListArray[i];
                self.title = self.beautifulEssayListArray[i].title;
            }
        }
    }
    
    if (self.beautifulEssayListArray) {
        for (NSInteger i = 0; i < self.beautifulEssayListArray.count; i++) {
            if ([self.beautifulEssayListArray[i].remoteUrl isEqualToString:navigationAction.request.URL.absoluteString]) {
                self.model = self.beautifulEssayListArray[i];
                self.title = self.beautifulEssayListArray[i].title;
            }
        }
    }

    if ([url containsString:@"http://buy.9ku.com/wap/goods"]) {
        if([[_UserM usercode] isEqualToString:@""]){
            [self gotoLogin];
        }else{
            LSZFindOutMoreVC *viewController = [[LSZFindOutMoreVC alloc] init];
            viewController.type = @"2";
            viewController.link = url;
            [self.navigationController pushViewController:viewController animated:YES];
        }
        decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转
        return;
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
#pragma mark -  加载完成时调用  -
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    if (_progressLayer == nil) {
        _progressLayer = [WYWebProgressLayer layerWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, 2)];
        [self.view.layer addSublayer:_progressLayer];
    }
    [_progressLayer startLoad];
}

///加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [_progressLayer finishedLoad];
    [self sendUserCode];
    //获取Title
    NSMutableString *javascript = [NSMutableString string];
    [javascript appendString:@"var titles=document.getElementsByTagName('h1');window.webkit.messageHandlers.title.postMessage(titles[0].innerHTML);"];
    [webView evaluateJavaScript:javascript completionHandler:nil];
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    Reachability *reach = [Reachability reachabilityWithHostName:webView.URL.absoluteString];
    if ([reach currentReachabilityStatus] != NotReachable){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.webView reloadFromOrigin];
        });
    }else{
        if ([webView.URL.absoluteString isEqualToString:@"about:blank"]) {
            
        }else{
            [super example1];
        }
    }
    [_progressLayer finishedLoad];
}

/// 提示框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示框" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

#pragma mark -  评论
- (void)keyboardChangedWithTransition:(YYKeyboardTransition)transition {
    CGRect frame = _manager.keyboardFrame;
    frame = [_manager convertRect:frame toView:self.view];
    
    // 获取键盘当前状态
    BOOL visible = _manager.keyboardVisible;
    
    if (visible) {
        
    }else{
        ///MARK:-
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.3];
        if (iPhoneX) {
            [self.lowView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(self.view);
                make.top.equalTo(self.view).offset(ScreenHeight-self.lowView.frame.size.height-15);
                make.height.mas_equalTo(self.lowView.frame.size.height);
            }];
            //                self.lowView.frame = CGRectMake(0, ScreenHeight-self.lowView.frame.size.height-15, ScreenWidth, self.lowView.frame.size.height);
        }else{
            [self.lowView mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.left.right.equalTo(self.view);
                make.top.equalTo(self.view).offset(ScreenHeight-self.lowView.frame.size.height);
                make.height.mas_equalTo(self.lowView.frame.size.height);
            }];
            //                self.lowView.frame = CGRectMake(0, ScreenHeight-self.lowView.frame.size.height, ScreenWidth, self.lowView.frame.size.height);
        }
        [UIView commitAnimations];
        
    }
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    if([[_UserM usercode] isEqualToString:@""]){
        _checkLoginSum++;
        if (_checkLoginSum > 1) return;
        pushAccLoginVC;
        [self.view endEditing:YES];
        return;
    }
    
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [self.lowView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(ScreenHeight-self.lowView.frame.size.height-height);
        make.height.mas_equalTo(self.lowView.frame.size.height);
    }];
    [UIView commitAnimations];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{    //拖动前的起始坐标
    [self clickSingleTap];
}

-(void)clickSingleTap {
    [self.view endEditing:YES];
}

-(void)gotoLoginVC{
    if([[_UserM usercode] isEqualToString:@""]){
        [self clickSingleTap];
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"AccLogin" bundle:nil];
        UIViewController *controller = [sb instantiateInitialViewController];
        [self.navigationController pushViewController:controller animated:YES];
    }
}

-(NSMutableArray *)selectedData{
    if (_selectedData == nil) {
        _selectedData = [NSMutableArray array];
        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Videokeeps"] != nil) {
            [_selectedData addObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"Videokeeps"]];
        }
        NSLog(@"_selectedData = %@", _selectedData);
    }
    return _selectedData;
}

@end
